package org.bravo369.inflightxt.utils;

import java.util.Vector;

public class RunningAverageFilter {

  private long filterTimeLength;
  private Vector<Sample> samples;

  private class Sample {
    public long timestamp;
    public float sample;

    public Sample(long timestamp, float sample) {
      this.sample = sample;
      this.timestamp = timestamp;
    }

    public Sample(float sample) {
      this.sample = sample;
      timestamp = System.currentTimeMillis();
    }
  }

  public RunningAverageFilter(float filterTimeLength) {
    this.filterTimeLength = (long)filterTimeLength * 1000;
    samples = new Vector<Sample>();
  }

  public RunningAverageFilter() {
    filterTimeLength = 2000;
    samples = new Vector<Sample>();
  }

  public void AddSample(float sample, long timestamp) {
    samples.add(new Sample(timestamp, sample));
  }

  public void AddSample(float sample) {
    samples.add(new Sample(sample));
  }

  public float GetFilteredValue() {
    RemoveOldSamples();
    float sum = 0.0f;
    for (Sample sample: samples)
      sum += sample.sample;
    int count = samples.size();
    if (sum == 0.0f)
      return 0.0f;
    else
      return sum / samples.size();
  }

  private void RemoveOldSamples() {
    long lastValidTimestamp = System.currentTimeMillis() - filterTimeLength;
    Vector<Sample> itterableSamples = (Vector<Sample>)samples.clone();
    for (Sample sample: itterableSamples) {
      if (lastValidTimestamp > sample.timestamp)
        samples.remove(sample);
    }
  }

}
